package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Vector;

import javax.ejb.EJB;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.CandidateService;
import service.InterviewService;
import service.UserService;
import entityJPA.Candidate;
import entityJPA.Candidatecomment;

/**
 * Servlet implementation class CandidateCommentServlet
 */
@WebServlet("/CandidateCommentServlet")
public class CandidateCommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private CandidateService candService;

	@EJB
	private UserService userService;

	@EJB
	private InterviewService interviewService;

	private int idCandidate;

	private void loadList(HttpServletRequest request,
			HttpServletResponse response) {

		Vector<Candidatecomment> list = candService
				.getAllCandidatecommentsByID(idCandidate);
		HttpSession h = request.getSession();

		if (request.getParameter("next") != null) {
			h.setAttribute("index", (Integer) (h.getAttribute("index")) + 2);
		}

		h.setAttribute("listComments", list);
		if (h.getAttribute("index") == null
				|| (Integer) h.getAttribute("index") >= list.size())
			h.setAttribute("index", 0);
		try {
			request.getRequestDispatcher("./commentDisplay.jsp").forward(
					request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CandidateCommentServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession h = request.getSession();
		h.setAttribute("operationIsSuccesfulComm", "no");
		
		try{
			idCandidate = Integer.parseInt(request.getParameter("idCandidate"));
			if (candService.getCandidateById(idCandidate) != null) {
				loadList(request, response);
				doPost(request, response);
			} else {
				// code for the error idCandidate inexistent
				h.setAttribute("exceptionMessage","This candidate does not exist in the database.");
				response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
			}
		}catch(Exception e){
			h.setAttribute("exceptionMessage","This candidate does not exist in the database.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
		

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("addComment") != null) {
			addCommentCandidate(request, response);
		} else if (request.getParameter("editComment") != null) {
			editCommentCandidate(request, response);
		} else if (request.getParameter("deleteComment") != null) {
			removeCommentCandidate(request, response);
		}
	}

	private void addCommentCandidate(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		HttpSession h = request.getSession();
		try {

			if (interviewService.userHasInterviewWithCandidate((String) request
					.getSession().getAttribute("savedUserName"), idCandidate)) {
				Candidatecomment cc = new Candidatecomment();
				cc.setCandidateComment(request.getParameter("comment"));
				cc.setUser(userService.getUserByUserName((String) request
						.getSession().getAttribute("savedUserName")));

				cc.setCandidate(candService.getCandidateById(idCandidate));

				candService.addCandidatecomment(cc);
				h.setAttribute("operationIsSuccesfulComm", "yes");
				loadList(request, response);
			} else {
				h.setAttribute("exceptionMessage",
						"You don't have the permission to add a comment to this candidate");
				response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
			}

		} catch (Exception e) {
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");

		}

	}

	private void editCommentCandidate(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			String un = request.getParameter("username");
			if (un.equals(request.getSession().getAttribute("savedUserName"))) {
				Candidatecomment cc = new Candidatecomment();
				cc.setIdCandidateComment(Integer.parseInt(request
						.getParameter("idCandidateComment")));
				cc.setCandidateComment(request.getParameter("comment"));
				cc.setUser(userService.getUserByUserName((String) request
						.getSession().getAttribute("savedUserName")));
				cc.setCandidate(candService.getCandidateById(idCandidate));
				candService.editCandidatecomment(cc);
				request.getSession().setAttribute("operationIsSuccesfulComm", "yes");
				loadList(request, response);
			}

		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");

		}
	
	}

	private void removeCommentCandidate(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			String un = request.getParameter("username");
			if (un.equals(request.getSession().getAttribute("savedUserName"))) {

				Candidatecomment candComm = new Candidatecomment();
				candComm.setIdCandidateComment(Integer.parseInt(request
						.getParameter("idCandidateComment")));
				candService.removeCandidateComment(candComm);
				request.getSession().setAttribute("operationIsSuccesfulComm", "yes");
				loadList(request, response);
			}

		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");

		}
		
	}
}
